Header Ads

How do you write a Floyd triangle in Java?

 What is Floyd Triangle ?

Floyd's triangle is a triangular array of natural numbers, used in computer science education. It is named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, starting with a 1 in the top left corner:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15 

Code :

package com.StepTowardsCoding;

import java.util.Scanner;

public class Floyd {
static void FloydTriangle(int n){
int val = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(val + " ");
val++;
}
System.out.println();
}
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number of rows of Floyd Triangle : ");
int row = sc.nextInt();
FloydTriangle(row);
}
}

Output :

Number of rows of Floyd Triangle : 7
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21 
22 23 24 25 26 27 28 

Explanation :

Floyd Triangle can be printed using nested for loop. First for loop determines the row and second for loop determines the columns.

For queries Contact

Post a Comment

0 Comments